package com.atguigu.gmall.payment.receiver;

import com.atguigu.gmall.common.rabbit.config.MqConst;
import com.atguigu.gmall.enums.model.PaymentStatus;
import com.atguigu.gmall.enums.model.PaymentType;
import com.atguigu.gmall.payment.model.PaymentInfo;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: atguigu
 * @create: 2023-05-12 15:13
 */
@Slf4j
@Component
public class PaymentReceiver {

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private AlipayService alipayService;

    /**
     * 超时未支付订单,监听关闭本地交易消息
     *
     * @param orderId
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_CLOSE, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_PAYMENT_CLOSE, durable = "true"),
            key = MqConst.ROUTING_PAYMENT_CLOSE
    ))
    public void procssPayClose(Long orderId, Channel channel, Message message) {
        try {
            if (orderId != null) {
                log.info("[支付服务]监听到关闭交易记录消息:{}", orderId);
                //1.根据订单ID查询本地交易记录
                PaymentInfo paymentInfo = paymentInfoService.getPaymentInfoByOrderId(orderId, PaymentType.ALIPAY.name());
                //2.判断本地交易记录状态 如果是:未支付 将状态改为关闭
                if (paymentInfo != null && PaymentStatus.UNPAID.name().equals(paymentInfo.getPaymentStatus())) {
                    paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
                    paymentInfoService.updateById(paymentInfo);

                    //3.查询支付宝端交易状态 如果是:等待支付 关闭支付宝交易记录
                    String status = alipayService.getZfbTradeState(paymentInfo.getTradeNo(), paymentInfo.getOutTradeNo());
                    if ("WAIT_BUYER_PAY".equals(status)) {
                        alipayService.closeZfbTrade(paymentInfo.getTradeNo(), paymentInfo.getOutTradeNo());
                    }
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("支付服务]监听到关闭交易记录处理异常:消息{}", e);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
